#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
整合的用户管理系统 - 支持管理员、买家、卖家三个角色
整合商品搜索、评价、管理功能
"""

import json
import time
import os
import sys
import hashlib
from typing import Dict, List, Optional
from datetime import datetime, timedelta

# 添加父目录到路径以支持导入
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

from json_translate import convert_excel_to_json
from recommendation_system import recommendation_system

# 导入购物车相关模块
from cart import Cart, CartItem

# 导入物流相关模块
import importlib.util
logistics_path = os.path.join(parent_dir, "new_models", "物流.py")
spec = importlib.util.spec_from_file_location("logistics_module", logistics_path)
logistics_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(logistics_module)
ShipmentManager = logistics_module.ShipmentManager
Shipment = logistics_module.Shipment

# 导入地图定位相关模块
map_code_dir = os.path.join(parent_dir, "new_models", "地图坐标获取", "code")
if map_code_dir not in sys.path:
    sys.path.insert(0, map_code_dir)

from calculate import get_lng_lat, get_road_distance
from akget import keyget

# 获取JSON文件路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXCEL_FILE_PATH = os.path.join(BASE_DIR, "data", "商品数据集.xlsx")
json_path = convert_excel_to_json(EXCEL_FILE_PATH)

# 用户数据文件路径
USERS_FILE_PATH = os.path.join(BASE_DIR, "users.json")

shipment_manager = ShipmentManager()


class User:
    """用户基类"""
    def __init__(self, user_id: str, username: str, password: str, email: str, phone: str, user_type: str):
        self.user_id = user_id
        self.username = username
        self.password = self._hash_password(password)
        self.email = email
        self.phone = phone
        self.user_type = user_type
        self.is_active = True
        self.created_at = datetime.now().strftime("%Y-%m-%d %H:%M")
    
    def _hash_password(self, password: str) -> str:
        """密码加密"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def verify_password(self, password: str) -> bool:
        """验证密码"""
        return self.password == self._hash_password(password)
    
    def to_dict(self) -> Dict:
        """转换为字典"""
        return {
            "user_id": self.user_id,
            "username": self.username,
            "password": self.password,
            "email": self.email,
            "phone": self.phone,
            "user_type": self.user_type,
            "is_active": self.is_active,
            "created_at": self.created_at
        }


class Customer(User):
    """买家类"""
    def __init__(self, user_id: str, username: str, password: str, email: str, phone: str):
        super().__init__(user_id, username, password, email, phone, "Customer")
        self.search_history = []
        self.favorite_products = []
        self.viewed_products = []  # 浏览过的商品
        self.purchased_products = []  # 购买过的商品
        self.cart = Cart()  # 购物车
        self.orders = []  # 订单列表
    
    def add_search_history(self, keyword: str, results_count: int):
        """添加搜索历史"""
        search_record = {
            "keyword": keyword,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "results_count": results_count
        }
        if not self.search_history or self.search_history[-1]["keyword"] != keyword:
            self.search_history.append(search_record)
            if len(self.search_history) > 10:
                self.search_history = self.search_history[-10:]
        
        # 记录搜索行为到推荐系统
        recommendation_system.behavior_tracker.record_search(
            self.user_id, keyword, results_count)
    
    def add_viewed_product(self, product_id: str):
        """添加浏览过的商品"""
        if product_id not in self.viewed_products:
            self.viewed_products.append(product_id)
            if len(self.viewed_products) > 50:
                self.viewed_products = self.viewed_products[-50:]
        
        # 记录浏览行为到推荐系统
        recommendation_system.behavior_tracker.record_view(self.user_id, product_id)
    
    def add_purchased_product(self, product_id: str, quantity: int = 1):
        """添加购买过的商品"""
        self.purchased_products.append({
            "product_id": product_id,
            "quantity": quantity,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
        
        # 记录购买行为到推荐系统
        recommendation_system.behavior_tracker.record_purchase(
            self.user_id, product_id, quantity)
    
    def get_recommendations(self, num_recommendations: int = 10, algorithm: str = "hybrid"):
        """获取推荐商品"""
        return recommendation_system.get_recommendations(
            self.user_id, num_recommendations, algorithm)
    
    def get_personalized_recommendations(self, num_recommendations: int = 10):
        """获取个性化推荐"""
        return recommendation_system.get_personalized_recommendations(
            self.user_id, num_recommendations)
    
    def get_category_recommendations(self, category: str, num_recommendations: int = 5):
        """获取特定类别的推荐"""
        return recommendation_system.get_category_recommendations(
            self.user_id, category, num_recommendations)
    
    def get_search_history(self):
        """获取搜索历史"""
        return self.search_history
    
    def to_dict(self) -> Dict:
        """转换为字典，包含订单和购物车数据"""
        base_dict = super().to_dict()
        # 添加Customer特有的属性
        base_dict.update({
            "search_history": self.search_history,
            "favorite_products": self.favorite_products,
            "viewed_products": self.viewed_products,
            "purchased_products": self.purchased_products,
            "cart": self.cart.to_dict(),  # 保存购物车数据
            "orders": getattr(self, 'orders', [])  # 保存订单数据
        })
        return base_dict


class Seller(User):
    """卖家类"""
    def __init__(self, user_id: str, username: str, password: str, email: str, phone: str, shop_name: str):
        super().__init__(user_id, username, password, email, phone, "Seller")
        self.shop_name = shop_name
        self.products = []
    
    def to_dict(self) -> Dict:
        """转换为字典"""
        base_dict = super().to_dict()
        base_dict["shop_name"] = self.shop_name
        return base_dict


class Admin(User):
    """管理员类"""
    def __init__(self, user_id: str, username: str, password: str, email: str, phone: str):
        super().__init__(user_id, username, password, email, phone, "Admin")


class Product:
    """商品类"""
    def __init__(self, 
                 name: str, 
                 province: str, 
                 prize: float, 
                 id_: str, 
                 province_id: str, 
                 merchant_id: str,
                 kind: str,
                 comments: Optional[List] = None,
                 modify_logs: Optional[List] = None
                 ):
        self.name = name
        self.province = province
        self.prize = prize
        self.id = id_
        self.province_id = province_id
        self.merchant_id = merchant_id
        self.kind = kind
        self.comments = comments or []
        self.modify_logs = modify_logs or []

    def add_comment(self, customer: Customer, comment_data: Dict) -> None:
        """添加评价"""
        new_comment = {
            "comment_id": f"cmt_{int(time.time())}",
            "customer_id": customer.user_id,
            "nickname": customer.username,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "product_rating": comment_data["商品满意度"],
            "merchant_rating": comment_data["商家满意度"],
            "logistics_rating": comment_data["物流满意度"],
            "text": comment_data["文字评价"],
            "likes": 0,
            "liked_by": [],
            "replies": [],
            "merchant_reply": None
        }
        self.comments.append(new_comment)
        self._save_to_file()
        print("评价提交成功！")

    def like_comment(self, customer: Customer, comment_id: str) -> bool:
        """点赞评价"""
        for comment in self.comments:
            if comment["comment_id"] == comment_id:
                if customer.user_id in comment["liked_by"]:
                    print("您已点赞过这条评价！")
                    return False
                comment["likes"] += 1
                comment["liked_by"].append(customer.user_id)
                self._save_to_file()
                print(f"点赞成功！当前点赞数：{comment['likes']}")
                return True
        print("未找到该评价！")
        return False

    def reply_to_comment(self, customer: Customer, comment_id: str, reply_text: str) -> bool:
        """回复评价"""
        for comment in self.comments:
            if comment["comment_id"] == comment_id:
                comment["replies"].append({
                    "reply_id": f"rpl_{int(time.time())}",
                    "customer_id": customer.user_id,
                    "nickname": customer.username,
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
                    "text": reply_text
                })
                self._save_to_file()
                print("回复成功！")
                return True
        print("未找到该评价！")
        return False

    def merchant_reply(self, seller: Seller, comment_id: str, reply_text: str) -> bool:
        """商家回复评价"""
        if seller.user_id != self.merchant_id:
            print("权限错误：您无权回复其他商家的商品评价！")
            return False
        
        for comment in self.comments:
            if comment["comment_id"] == comment_id:
                comment["merchant_reply"] = {
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
                    "text": reply_text,
                    "shop_name": seller.shop_name
                }
                self._save_to_file()
                print("回复成功！已显示为官方回复")
                return True
        print("未找到该评价！")
        return False

    def filter_comments(self, filter_type: str, sort_type: str) -> List:
        """筛选评价"""
        filtered = []
        for comment in self.comments:
            total = sum([
                len(comment["product_rating"]),
                len(comment["merchant_rating"]),
                len(comment["logistics_rating"])
            ])
            avg = total / 3

            if filter_type == "好评" and avg >= 4:
                filtered.append(comment)
            elif filter_type == "中评" and 2 < avg < 4:
                filtered.append(comment)
            elif filter_type == "差评" and avg <= 2:
                filtered.append(comment)
            elif filter_type == "全部":
                filtered.append(comment)

        if sort_type == "最新":
            return sorted(filtered, key=lambda x: x["timestamp"], reverse=True)
        elif sort_type == "最热":
            return sorted(filtered, key=lambda x: x["likes"] + len(x["replies"]), reverse=True)
        return filtered

    def update_info(self, seller: Seller, new_data: Dict, reason: str) -> bool:
        """修改商品信息"""
        if seller.user_id != self.merchant_id:
            print("权限错误：您无权修改其他商家的商品！")
            return False

        old_data = {}
        if "prize" in new_data:
            old_data["prize"] = self.prize
            self.prize = new_data["prize"]
        if "province" in new_data:
            old_data["province"] = self.province
            self.province = new_data["province"]

        self.modify_logs.append({
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "merchant_id": seller.user_id,
            "shop_name": seller.shop_name,
            "old_data": old_data,
            "new_data": new_data,
            "reason": reason
        })

        self._save_to_file()
        return True

    @classmethod
    def fuzzy_search(cls, keyword: str) -> List:
        """模糊搜索商品 - 只在商品名称中搜索，支持智能字符级模糊匹配"""
        products = cls._load_all_products()
        keyword = keyword.lower().strip()
        results = []
        
        # 过滤掉常见的无意义单字符
        meaningful_chars = ['子', '的', '了', '在', '是', '和', '有', '就', '与', '等', '或']
        
        for p in products:
            score = 0
            name_lower = p.name.lower()
            
            # 只在商品名称中搜索，不考虑其他字段
            
            # 优先：完整关键词匹配（高优先级）
            if keyword in name_lower:
                if name_lower == keyword:
                    score += 100  # 完全匹配 - 最高分
                elif name_lower.startswith(keyword):
                    score += 80   # 开头匹配
                else:
                    score += 50   # 包含匹配
            
            # 字符级模糊匹配
            else:
                # 查找所有可能的连续子串
                max_consecutive_match = 0
                for i in range(len(keyword)):
                    for j in range(i + 1, len(keyword) + 1):
                        substring = keyword[i:j]
                        if substring in name_lower:
                            max_consecutive_match = max(max_consecutive_match, len(substring))
                
                # 计算匹配的字符及优先级
                matched_chars = []
                for char in keyword:
                    if char in name_lower:
                        matched_chars.append(char)
                
                # 如果找到连续的字符匹配（至少1个字符）
                if max_consecutive_match >= 1:
                    match_ratio = max_consecutive_match / len(keyword)
                    score += int(30 * match_ratio)
                    
                    # 如果只匹配了一个字符且是"子"，不给予单独分数
                    if max_consecutive_match == 1 and matched_chars == ['子']:
                        score = 0
                
                # 额外的字符匹配检查
                elif len(matched_chars) > 0:
                    # 计算有意义字符的匹配数量
                    meaningful_match_count = 0
                    meaningful_matched = []
                    for char in keyword:
                        if char not in meaningful_chars and char in name_lower:
                            meaningful_match_count += 1
                            meaningful_matched.append(char)
                    
                    # 如果匹配了至少一个有意义的字符，给予分数
                    if meaningful_match_count >= 1:
                        score += int(10 * (meaningful_match_count / len(keyword)))
                    # 如果只匹配了"子"，不给予分数
                    elif matched_chars == ['子']:
                        score = 0
            
            # 只返回商品名称匹配的结果
            if score > 0:
                results.append((p, score))
        
        return [p for p, _ in sorted(results, key=lambda x: (-x[1], x[0].name))]

    @classmethod
    def advanced_search(cls, search_criteria: Dict) -> List:
        """高级搜索"""
        products = cls._load_all_products()
        results = []
        
        for p in products:
            match = True
            
            if 'name' in search_criteria and search_criteria['name']:
                if search_criteria['name'].lower() not in p.name.lower():
                    match = False
            
            if 'kind' in search_criteria and search_criteria['kind']:
                if search_criteria['kind'].lower() not in p.kind.lower():
                    match = False
            
            if 'province' in search_criteria and search_criteria['province']:
                if search_criteria['province'].lower() not in p.province.lower():
                    match = False
            
            if 'min_price' in search_criteria and search_criteria['min_price']:
                if p.prize < search_criteria['min_price']:
                    match = False
            
            if 'max_price' in search_criteria and search_criteria['max_price']:
                if p.prize > search_criteria['max_price']:
                    match = False
            
            if match:
                results.append(p)
        
        return results

    @classmethod
    def from_name(cls, name: str):
        """通过名称获取商品"""
        products = cls._load_all_products()
        for p in products:
            if p.name == name:
                return p
        return None

    @classmethod
    def get_merchant_products(cls, merchant_id: str) -> List:
        """获取商家商品"""
        all_products = cls._load_all_products()
        return [p for p in all_products if p.merchant_id == merchant_id]

    @classmethod
    def _load_all_products(cls) -> List:
        """加载所有商品"""
        try:
            # 使用动态路径
            import os
            BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            json_file_path = os.path.join(BASE_DIR, "data", "商品数据集.json")
            with open(json_file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            products = []
            for item in data:
                kind_cls = {
                    "Food": Food,
                    "Clothing": Clothing,
                    "Book": Book,
                    "Electronic Products": ElectronicProducts,
                    "Daily product": DailyProduct
                }.get(item["Kind"], Product)
                
                product = kind_cls(
                    name=item["Name"],
                    province=item["Province"],
                    prize=item["Prize（yuan)"],
                    id_=item["ID"],
                    province_id=item["ProvinceID"],
                    merchant_id=item.get("MerchantID", ""),
                    kind=item["Kind"],
                    comments=item.get("Comments", []),
                    modify_logs=item.get("ModifyLogs", [])
                )
                products.append(product)
            return products
        except (FileNotFoundError, json.JSONDecodeError):
            return []

    def _save_to_file(self) -> None:
        """保存商品数据"""
        all_products = [p.to_dict() for p in self._load_all_products() if p.id != self.id]
        all_products.append(self.to_dict())
        
        # 使用动态路径
        import os
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        json_file_path = os.path.join(BASE_DIR, "data", "商品数据集.json")
        with open(json_file_path, 'w', encoding='utf-8') as f:
            json.dump(all_products, f, ensure_ascii=False, indent=2)

    @classmethod
    def from_id(cls, product_id: str):
        """通过ID获取商品"""
        products = cls._load_all_products()
        for p in products:
            if p.id == product_id:
                return p
        return None

    def to_dict(self) -> Dict:
        """转换为字典"""
        return {
            "Name": self.name,
            "Province": self.province,
            "Prize（yuan)": self.prize,
            "ID": self.id,
            "ProvinceID": self.province_id,
            "MerchantID": self.merchant_id,
            "Kind": self.kind,
            "Comments": self.comments,
            "ModifyLogs": self.modify_logs
        }


# 商品子类
class Food(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Clothing(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Book(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class ElectronicProducts(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class DailyProduct(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


class UserManager:
    """用户管理器"""
    def __init__(self):
        self.users = {}
        self.current_user = None
        self._load_users()
    
    def _load_users(self):
        """加载用户数据"""
        try:
            with open(USERS_FILE_PATH, 'r', encoding='utf-8') as f:
                users_data = json.load(f)
                for user_data in users_data:
                    # 如果没有密码字段，使用默认密码
                    password = user_data.get("password", "123456")
                    
                    if user_data["user_type"] == "Customer":
                        user = Customer(
                            user_data["user_id"],
                            user_data["username"],
                            password,
                            user_data["email"],
                            user_data["phone"]
                        )
                        # 恢复购物车和订单数据
                        if "cart" in user_data:
                            user.cart = Cart.from_dict(user_data["cart"])
                        if "orders" in user_data:
                            user.orders = user_data["orders"]
                        # 恢复其他历史数据
                        if "search_history" in user_data:
                            user.search_history = user_data["search_history"]
                        if "viewed_products" in user_data:
                            user.viewed_products = user_data["viewed_products"]
                        if "purchased_products" in user_data:
                            user.purchased_products = user_data["purchased_products"]
                    elif user_data["user_type"] == "Seller":
                        user = Seller(
                            user_data["user_id"],
                            user_data["username"],
                            password,
                            user_data["email"],
                            user_data["phone"],
                            user_data.get("shop_name", "默认店铺")
                        )
                    elif user_data["user_type"] == "Admin":
                        user = Admin(
                            user_data["user_id"],
                            user_data["username"],
                            password,
                            user_data["email"],
                            user_data["phone"]
                        )
                    else:
                        continue
                    
                    # 直接设置已哈希的密码，避免双重哈希
                    user.password = password
                    user.is_active = user_data.get("is_active", True)
                    user.created_at = user_data.get("created_at", datetime.now().strftime("%Y-%m-%d %H:%M"))
                    self.users[user.user_id] = user
        except (FileNotFoundError, json.JSONDecodeError):
            # 创建默认管理员账户
            admin = Admin("admin001", "admin", "admin123", "admin@example.com", "00000000000")
            self.users[admin.user_id] = admin
            self.save_users()
    
    def save_users(self):
        """保存用户数据"""
        users_data = [user.to_dict() for user in self.users.values()]
        with open(USERS_FILE_PATH, 'w', encoding='utf-8') as f:
            json.dump(users_data, f, ensure_ascii=False, indent=2)
    
    def register_user(self, user_type: str, username: str, password: str, email: str, phone: str, **kwargs):
        """注册用户"""
        # 检查用户名是否已存在
        for user in self.users.values():
            if user.username == username:
                return None, "用户名已存在"
        
        user_id = f"{user_type[0].lower()}{len(self.users) + 1:03d}"
        
        if user_type == "Customer":
            user = Customer(user_id, username, password, email, phone)
        elif user_type == "Seller":
            shop_name = kwargs.get("shop_name", "")
            if not shop_name:
                return None, "店铺名称不能为空"
            user = Seller(user_id, username, password, email, phone, shop_name)
        elif user_type == "Admin":
            user = Admin(user_id, username, password, email, phone)
        else:
            return None, "无效的用户类型"
        
        self.users[user.user_id] = user
        self.save_users()
        return user, "注册成功"
    
    def login_user(self, username: str, password: str):
        """用户登录"""
        for user in self.users.values():
            if user.username == username and user.verify_password(password) and user.is_active:
                self.current_user = user
                return user, "登录成功"
        return None, "用户名或密码错误"
    
    def logout_user(self):
        """用户登出"""
        self.current_user = None
    
    def get_user_by_id(self, user_id: str):
        """通过ID获取用户"""
        return self.users.get(user_id)
    
    def get_all_users(self):
        """获取所有用户"""
        return list(self.users.values())
    
    def get_users_by_type(self, user_type: str):
        """根据类型获取用户"""
        return [user for user in self.users.values() if user.user_type == user_type]


# 全局用户管理器实例
user_manager = UserManager()


def display_search_results(products: List, customer: Customer, keyword: str):
    """显示搜索结果并让用户选择"""
    if not products:
        print("未找到匹配的商品！")
        customer.add_search_history(keyword, 0)
        return None
    
    customer.add_search_history(keyword, len(products))
    
    print(f"\n🔍 搜索关键词：'{keyword}'")
    print(f"📊 找到 {len(products)} 个匹配商品：")
    print("=" * 60)
    
    for i, p in enumerate(products, 1):
        print(f"{i:2d}. 📦 {p.name}")
        print(f"     💰 价格：{p.prize}元")
        print(f"     🏷️  类别：{p.kind}  📍 产地：{p.province}")
        print(f"     🆔 ID：{p.id}")
        print("-" * 40)
    
    while True:
        try:
            choice = input(f"\n请选择要查看的商品（输入序号 1-{len(products)}，或输入 0 返回）：").strip()
            if choice == "0":
                return None
            
            idx = int(choice) - 1
            if 0 <= idx < len(products):
                selected_product = products[idx]
                # 记录用户浏览行为
                customer.add_viewed_product(selected_product.id)
                return selected_product
            else:
                print(f"请输入 1-{len(products)} 之间的数字！")
        except ValueError:
            print("请输入有效的数字！")
        except KeyboardInterrupt:
            print("\n操作已取消")
            return None


def show_product_details(product: Product, customer: Customer):
    """显示商品详情并处理用户操作"""
    while True:
        print("\n" + "="*60)
        print(f"📦 商品详情：{product.name}")
        print("="*60)
        print(f"💰 价格：{product.prize}元")
        print(f"🏷️  类别：{product.kind}")
        print(f"📍 产地：{product.province}（{product.province_id}）")
        print(f"🆔 商品ID：{product.id}")
        print(f"👤 商家ID：{product.merchant_id}")
        
        print("\n📝 评价操作：")
        print("1. 👀 查看评价")
        print("2. ✍️  添加评价")
        print("3. 🔙 返回主菜单")
        
        choice = input("\n请选择操作（1-3）：").strip()
        
        if choice == "1":
            show_product_comments(product, customer)
        elif choice == "2":
            add_product_comment(product, customer)
        elif choice == "3":
            break
        else:
            print("❌ 输入无效，请重新选择！")


def show_product_comments(product: Product, customer: Customer):
    """显示商品评价"""
    if not product.comments:
        print("\n📝 暂无评价！")
        return
    
    print("\n📝 评价筛选：")
    print("1. 全部评价  2. 好评  3. 中评  4. 差评")
    filter_choice = input("请选择评价类型（1-4）：").strip()
    filter_map = {"1": "全部", "2": "好评", "3": "中评", "4": "差评"}
    filter_type = filter_map.get(filter_choice, "全部")
    
    print("\n📊 排序方式：")
    print("1. 最新  2. 最热")
    sort_choice = input("请选择排序方式（1-2）：").strip()
    sort_map = {"1": "最新", "2": "最热"}
    sort_type = sort_map.get(sort_choice, "最新")
    
    filtered = product.filter_comments(filter_type, sort_type)
    print(f"\n📝 {filter_type}评价（{sort_type}排序）")
    print("="*50)
    
    for i, cmt in enumerate(filtered, 1):
        print(f"{i:2d}. 👤 {cmt['nickname']}（{cmt['timestamp']}）")
        print(f"     ⭐ 评分：商品{cmt['product_rating']} 商家{cmt['merchant_rating']} 物流{cmt['logistics_rating']}")
        print(f"     💬 评价：{cmt['text']}")
        if cmt["merchant_reply"]:
            print(f"     🏪 商家回复：{cmt['merchant_reply']['text']}（{cmt['merchant_reply']['timestamp']}）")
        print(f"     👍 点赞：{cmt['likes']} | 💬 回复：{len(cmt['replies'])}")
        print("-" * 40)
    
    if filtered:
        try:
            cmt_idx = int(input(f"\n选择要互动的评价（1-{len(filtered)}，0返回）：").strip()) - 1
            if cmt_idx == -1:
                return
            target_cmt = filtered[cmt_idx]
            
            action = input("选择操作（1.点赞 2.回复）：").strip()
            if action == "1":
                product.like_comment(customer, target_cmt["comment_id"])
            elif action == "2":
                reply_text = input("请输入回复内容：").strip()
                product.reply_to_comment(customer, target_cmt["comment_id"], reply_text)
            else:
                print("❌ 输入无效！")
        except (ValueError, IndexError):
            print("❌ 输入无效！")


def add_product_comment(product: Product, customer: Customer):
    """添加商品评价"""
    print("\n✍️ 添加评价")
    print("-" * 30)
    try:
        product_score = int(input("1. 商品满意度（1-5星）：").strip())
        merchant_score = int(input("2. 商家满意度（1-5星）：").strip())
        logistics_score = int(input("3. 物流满意度（1-5星）：").strip())
        
        if not (1 <= product_score <= 5 and 1 <= merchant_score <= 5 and 1 <= logistics_score <= 5):
            raise ValueError
        
        text = input("4. 文字评价：").strip()
        
        product.add_comment(customer, {
            "商品满意度": "★" * product_score,
            "商家满意度": "★" * merchant_score,
            "物流满意度": "★" * logistics_score,
            "文字评价": text
        })
    except ValueError:
        print("❌ 评分必须是1-5之间的数字！")


def create_single_product_order(customer, item, recipient_name, recipient_phone, 
                                dest_address, dest_lng, dest_lat, ak):
    """
    为单个商品创建订单
    
    参数:
        customer: 客户对象
        item: 购物车商品项
        recipient_name: 收件人姓名
        recipient_phone: 收件人电话
        dest_address: 收货地址
        dest_lng: 收货地经度
        dest_lat: 收货地纬度
        ak: 百度地图API密钥
        
    返回:
        tuple: (是否成功, 订单数据或错误信息)
    """
    try:
        # 获取商品发货地址
        origin_address = get_product_origin_address(item.product_id)
        if not origin_address:
            origin_address = "陕西省西安市长安区长安大学渭水校区"
            print(f"  ⚠️  {item.product_name}: 使用默认发货地址")
        
        # 定位发货地址
        origin_lng_lat = get_lng_lat(origin_address, ak)
        if not isinstance(origin_lng_lat, tuple):
            origin_lng, origin_lat = 108.92005707541986, 34.37819513808234
        else:
            origin_lng, origin_lat = origin_lng_lat
        
        # 计算距离和预计耗时
        road_info = get_road_distance(origin_lng, origin_lat, dest_lng, dest_lat, ak)
        distance = road_info['distance_km']
        duration = road_info['duration_h']
        
        # 预计到货日期
        est_days = max(1, int(duration // 24 + 1))
        est_date = (datetime.now() + timedelta(days=est_days)).strftime('%Y-%m-%d')
        
        # 计算运费（每个商品单独计算）
        shipping_fee = max(5, round(distance * 0.5, 2))
        item_amount = item.get_total()
        final_amount = item_amount + shipping_fee
        
        # 创建订单ID和物流单号
        order_id = f"ORD{int(time.time())}{customer.user_id[-3:]}{item.product_id[:3]}"
        tracking_number = f"TRK{int(time.time())}{item.product_id[:3]}"
        
        # 构建订单数据
        order_data = {
            "order_id": order_id,
            "tracking_number": tracking_number,
            "items": [{
                "product_id": item.product_id,
                "product_name": item.product_name,
                "quantity": item.quantity,
                "price": item.price,
                "total": item.get_total(),
                "origin_address": origin_address
            }],
            "total_amount": item_amount,
            "base_shipping_fee": shipping_fee,
            "multi_origin_fee": 0,  # 单商品订单无多发货地费用
            "shipping_fee": shipping_fee,
            "final_amount": final_amount,
            "shipping_address": {
                "address": dest_address,
                "recipient_name": recipient_name,
                "recipient_phone": recipient_phone,
                "longitude": dest_lng,
                "latitude": dest_lat
            },
            "origin_addresses": [origin_address],
            "main_origin_address": {
                "address": origin_address,
                "longitude": origin_lng,
                "latitude": origin_lat
            },
            "logistics": {
                "distance_km": distance,
                "duration_h": duration,
                "estimated_days": est_days,
                "estimated_date": est_date,
                "origin_count": 1
            },
            "status": "Processing",
            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        return True, order_data, {
            "order_id": order_id,
            "tracking_number": tracking_number,
            "distance": distance,
            "shipping_fee": shipping_fee,
            "final_amount": final_amount,
            "est_date": est_date,
            "origin_address": origin_address
        }
    
    except Exception as e:
        return False, f"创建订单失败：{str(e)}", None


def checkout_selected_items_separately(customer, selected_items, cart):
    """
    为选中的商品分别创建订单（每个商品单独下单）
    
    参数:
        customer: 客户对象
        selected_items: 选中的商品列表
        cart: 购物车对象
    """
    print("\n" + "="*60)
    print("🛒 选中商品结算（每个商品单独创建订单）")
    print("="*60)
    
    # 显示选中的商品
    print(f"\n将为以下 {len(selected_items)} 个商品分别创建订单：")
    for i, item in enumerate(selected_items, 1):
        print(f"{i}. 📦 {item.product_name} x{item.quantity} = {item.get_total()}元")
    
    total_amount = sum(item.get_total() for item in selected_items)
    print(f"\n💰 商品总金额：{total_amount}元")
    print("⚠️  注意：每个商品将单独计算运费并创建订单")
    
    confirm = input("\n是否确认下单？(y/n)：").strip().lower()
    if confirm != 'y':
        print("❌ 已取消下单")
        return
    
    # 输入收货地址（所有订单共用）
    print("\n📍 收货地址信息")
    print("-" * 40)
    dest_address = input("请输入详细收货地址：").strip()
    if not dest_address:
        print("❌ 收货地址不能为空！")
        return
    
    recipient_name = input("收件人姓名：").strip()
    recipient_phone = input("收件人电话：").strip()
    
    # 地址定位
    print("\n🔍 正在定位收货地址...")
    ak = keyget()
    lng_lat = get_lng_lat(dest_address, ak)
    
    if not isinstance(lng_lat, tuple):
        print(f"❌ 地址定位失败！请输入更详细的地址")
        return
    
    dest_lng, dest_lat = lng_lat
    print(f"✓ 地址定位成功：经度 {dest_lng}, 纬度 {dest_lat}")
    
    # 为每个商品单独创建订单
    print("\n" + "="*60)
    print("📦 正在为每个商品创建订单...")
    print("="*60)
    
    if not hasattr(customer, 'orders'):
        customer.orders = []
    
    successful_orders = []
    failed_orders = []
    total_shipping_fee = 0
    
    for i, item in enumerate(selected_items, 1):
        print(f"\n[{i}/{len(selected_items)}] 处理：{item.product_name}")
        print("-" * 40)
        
        success, order_data, summary = create_single_product_order(
            customer, item, recipient_name, recipient_phone,
            dest_address, dest_lng, dest_lat, ak
        )
        
        if success:
            customer.orders.append(order_data)
            successful_orders.append(summary)
            total_shipping_fee += summary['shipping_fee']
            
            # 显示订单信息
            print(f"✅ 订单创建成功！")
            print(f"  订单编号：{summary['order_id']}")
            print(f"  物流单号：{summary['tracking_number']}")
            print(f"  发货地：{summary['origin_address']}")
            print(f"  配送距离：{summary['distance']}公里")
            print(f"  运费：{summary['shipping_fee']}元")
            print(f"  实付金额：{summary['final_amount']}元")
            print(f"  预计送达：{summary['est_date']}")
            
            # 记录购买行为
            customer.add_purchased_product(item.product_id, item.quantity)
        else:
            failed_orders.append({
                'product_name': item.product_name,
                'error': order_data
            })
            print(f"❌ {order_data}")
    
    # 显示总结
    print("\n" + "="*60)
    print("📊 下单总结")
    print("="*60)
    print(f"成功创建订单：{len(successful_orders)}个")
    print(f"失败：{len(failed_orders)}个")
    
    if successful_orders:
        final_total = sum(s['final_amount'] for s in successful_orders)
        print(f"\n💰 商品总金额：{total_amount}元")
        print(f"💰 运费总计：{total_shipping_fee}元")
        print(f"💰 实付总金额：{final_total}元")
        
        print(f"\n📦 订单列表：")
        for j, s in enumerate(successful_orders, 1):
            print(f"{j}. 订单 {s['order_id']} - 实付 {s['final_amount']}元")
    
    if failed_orders:
        print(f"\n❌ 失败的商品：")
        for j, f in enumerate(failed_orders, 1):
            print(f"{j}. {f['product_name']} - {f['error']}")
    
    # 从购物车中移除成功下单的商品
    if successful_orders:
        successful_product_ids = [item.product_id for item in selected_items 
                                  if any(s['order_id'].endswith(item.product_id[:3]) 
                                        for s in successful_orders)]
        
        cart.items = [item for item in cart.items 
                     if item.product_id not in successful_product_ids]
        
        print(f"\n✅ 已从购物车中移除{len(successful_product_ids)}件已下单商品")
        
        # 保存用户数据
        user_manager.save_users()
        print("✅ 订单信息已保存")
    
    input("\n按回车键返回...")


def get_product_origin_address(product_id):
    """
    根据商品ID获取商品的发货地址（Province字段）
    
    参数:
        product_id: 商品ID
        
    返回:
        str: 发货地址，如果找不到则返回None
    """
    try:
        product = Product.from_id(product_id)
        if product:
            return product.province
        return None
    except Exception as e:
        print(f"获取商品发货地址失败：{str(e)}")
        return None


def cart_checkout_and_logistics(customer):
    """购物车下单并进入物流流程 - 从商品数据集获取发货地址"""
    cart = getattr(customer, 'cart', None)
    if not cart or not cart.items:
        print("\n❌ 购物车为空！")
        return
    
    print("\n" + "="*60)
    print("🛒 购物车结算")
    print("="*60)
    
    # 显示购物车商品
    for i, item in enumerate(cart.items, 1):
        print(f"{i}. 📦 {item.product_name}")
        print(f"   数量：{item.quantity} | 单价：{item.price}元 | 小计：{item.get_total()}元")
        print("-" * 40)
    
    total_amount = cart.calculate_total()
    print(f"\n💰 订单总金额：{total_amount}元")
    
    confirm = input("\n是否确认下单？(y/n)：").strip().lower()
    if confirm != 'y':
        print("❌ 已取消下单")
        return
    
    # 输入收货地址
    print("\n📍 收货地址信息")
    print("-" * 40)
    address = input("请输入详细收货地址：").strip()
    if not address:
        print("❌ 收货地址不能为空！")
        return
    
    recipient_name = input("收件人姓名：").strip()
    recipient_phone = input("收件人电话：").strip()
    
    # 地址定位
    print("\n🔍 正在定位收货地址...")
    ak = keyget()
    lng_lat = get_lng_lat(address, ak)
    
    if not isinstance(lng_lat, tuple):
        print(f"❌ 地址定位失败！请输入更详细的地址")
        return
    
    dest_lng, dest_lat = lng_lat
    print(f"✓ 地址定位成功：经度 {dest_lng}, 纬度 {dest_lat}")
    
    # 按商品分组计算物流（相同产地的商品合并计算）
    print("\n📦 正在获取商品发货信息...")
    
    # 收集所有商品的发货地址
    origin_addresses = {}  # {发货地址: [商品列表]}
    for item in cart.items:
        origin_address = get_product_origin_address(item.product_id)
        if not origin_address:
            print(f"⚠️  警告：无法获取商品 {item.product_name} 的发货地址，使用默认地址")
            origin_address = "陕西省西安市长安区长安大学渭水校区"
        
        if origin_address not in origin_addresses:
            origin_addresses[origin_address] = []
        origin_addresses[origin_address].append(item)
    
    # 显示发货地信息
    print(f"\n📍 本订单涉及 {len(origin_addresses)} 个发货地：")
    for i, (addr, items) in enumerate(origin_addresses.items(), 1):
        product_names = [item.product_name for item in items]
        print(f"{i}. {addr}")
        print(f"   商品：{', '.join(product_names)}")
    
    # 计算物流信息（使用主要发货地或第一个发货地）
    # 如果有多个发货地，选择商品数量最多的作为主发货地
    main_origin_address = max(origin_addresses.items(), key=lambda x: len(x[1]))[0]
    
    if len(origin_addresses) > 1:
        print(f"\n📌 以主发货地 '{main_origin_address}' 计算物流费用")
    
    # 计算距离和预计耗时
    print("\n📏 正在计算物流信息...")
    try:
        # 定位发货地址
        origin_lng_lat = get_lng_lat(main_origin_address, ak)
        if not isinstance(origin_lng_lat, tuple):
            print(f"⚠️  发货地址定位失败，使用默认坐标")
            origin_lng, origin_lat = 108.92005707541986, 34.37819513808234
            main_origin_address = "陕西省西安市长安区长安大学渭水校区"
        else:
            origin_lng, origin_lat = origin_lng_lat
            print(f"✓ 发货地定位成功：经度 {origin_lng}, 纬度 {origin_lat}")
        
        road_info = get_road_distance(origin_lng, origin_lat, dest_lng, dest_lat, ak)
        distance = road_info['distance_km']
        duration = road_info['duration_h']
        
        print("\n" + "="*60)
        print("📦 物流信息")
        print("="*60)
        print(f"主发货地：{main_origin_address}")
        print(f"收货地：{address}")
        print(f"收件人：{recipient_name} ({recipient_phone})")
        print(f"实际道路距离：{distance}公里")
        print(f"预计运输耗时：{duration}小时")
        
        # 预计到货日期
        est_days = max(1, int(duration // 24 + 1))
        est_date = (datetime.now() + timedelta(days=est_days)).strftime('%Y-%m-%d')
        
        # 计算运费（基础运费 + 距离运费）
        # 如果有多个发货地，增加额外费用
        base_shipping_fee = max(5, round(distance * 0.5, 2))
        multi_origin_fee = (len(origin_addresses) - 1) * 3  # 每多一个发货地加3元
        shipping_fee = base_shipping_fee + multi_origin_fee
        final_amount = total_amount + shipping_fee
        
        if multi_origin_fee > 0:
            print(f"\n💰 基础运费：{base_shipping_fee}元")
            print(f"💰 多发货地附加费：{multi_origin_fee}元（{len(origin_addresses)}个发货地）")
            print(f"💰 总运费：{shipping_fee}元")
        else:
            print(f"\n💰 运费：{shipping_fee}元")
        
        print(f"💰 实付金额：{final_amount}元")
        print(f"📅 预计送达：{est_date}（{est_days}天）")
        
        # 创建订单ID
        order_id = f"ORD{int(time.time())}{customer.user_id[-3:]}"
        tracking_number = f"TRK{int(time.time())}"
        
        print(f"\n🆔 订单编号：{order_id}")
        print(f"🆔 物流单号：{tracking_number}")
        
        # 保存订单信息到用户对象（简化处理）
        if not hasattr(customer, 'orders'):
            customer.orders = []
        
        # 构建商品信息，包含发货地
        items_with_origin = []
        for item in cart.items:
            origin_addr = get_product_origin_address(item.product_id)
            items_with_origin.append({
                "product_id": item.product_id,
                "product_name": item.product_name,
                "quantity": item.quantity,
                "price": item.price,
                "total": item.get_total(),
                "origin_address": origin_addr or "未知"
            })
        
        order_data = {
            "order_id": order_id,
            "tracking_number": tracking_number,
            "items": items_with_origin,
            "total_amount": total_amount,
            "base_shipping_fee": base_shipping_fee,
            "multi_origin_fee": multi_origin_fee,
            "shipping_fee": shipping_fee,
            "final_amount": final_amount,
            "shipping_address": {
                "address": address,
                "recipient_name": recipient_name,
                "recipient_phone": recipient_phone,
                "longitude": dest_lng,
                "latitude": dest_lat
            },
            "origin_addresses": list(origin_addresses.keys()),
            "main_origin_address": {
                "address": main_origin_address,
                "longitude": origin_lng,
                "latitude": origin_lat
            },
            "logistics": {
                "distance_km": distance,
                "duration_h": duration,
                "estimated_days": est_days,
                "estimated_date": est_date,
                "origin_count": len(origin_addresses)
            },
            "status": "Processing",
            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        customer.orders.append(order_data)
        
        # 记录购买行为
        for item in cart.items:
            customer.add_purchased_product(item.product_id, item.quantity)
        
        print("\n" + "="*60)
        print("✅ 订单创建成功！")
        print("="*60)
        print("您可以在 '我的订单' 中查看物流进度")
        
        # 清空购物车
        cart.items.clear()
        print("\n🛒 购物车已清空")
        
        # 保存用户数据
        user_manager.save_users()
        
    except Exception as e:
        print(f"\n❌ 物流信息计算失败：{str(e)}")
        import traceback
        traceback.print_exc()
        print("请稍后重试或联系客服")


def view_my_orders(customer: Customer):
    """查看我的订单"""
    orders = getattr(customer, 'orders', [])
    
    if not orders:
        print("\n📦 暂无订单记录")
        return
    
    print("\n" + "="*60)
    print("📦 我的订单")
    print("="*60)
    
    for i, order in enumerate(reversed(orders), 1):
        print(f"\n【订单 {i}】")
        print(f"🆔 订单编号：{order['order_id']}")
        print(f"🆔 物流单号：{order['tracking_number']}")
        print(f"📅 下单时间：{order['created_at']}")
        print(f"📍 状态：{order['status']}")
        
        print(f"\n商品清单：")
        for item in order['items']:
            # 显示商品及其发货地
            if isinstance(item, dict) and 'origin_address' in item:
                print(f"  - {item['product_name']} x{item['quantity']} = {item['total']}元")
                print(f"    📍 发货地：{item['origin_address']}")
            else:
                # 兼容旧订单格式
                print(f"  - {item.get('product_name', '未知商品')} x{item.get('quantity', 0)} = {item.get('total', 0)}元")
        
        print(f"\n💰 商品金额：{order['total_amount']}元")
        
        # 显示运费详情
        if 'base_shipping_fee' in order and 'multi_origin_fee' in order:
            print(f"💰 基础运费：{order['base_shipping_fee']}元")
            if order['multi_origin_fee'] > 0:
                print(f"💰 多发货地附加费：{order['multi_origin_fee']}元")
            print(f"💰 总运费：{order['shipping_fee']}元")
        else:
            print(f"💰 运费：{order['shipping_fee']}元")
        
        print(f"💰 实付金额：{order['final_amount']}元")
        
        print(f"\n📍 收货信息：")
        print(f"  收件人：{order['shipping_address']['recipient_name']}")
        print(f"  电话：{order['shipping_address']['recipient_phone']}")
        print(f"  地址：{order['shipping_address']['address']}")
        
        print(f"\n📦 物流信息：")
        
        # 显示发货地信息
        if 'origin_addresses' in order and len(order['origin_addresses']) > 0:
            if len(order['origin_addresses']) == 1:
                print(f"  发货地：{order['origin_addresses'][0]}")
            else:
                print(f"  发货地（{len(order['origin_addresses'])}个）：")
                for j, addr in enumerate(order['origin_addresses'], 1):
                    print(f"    {j}. {addr}")
        elif 'origin_address' in order:
            # 兼容旧格式
            print(f"  发货地：{order['origin_address'].get('address', '未知')}")
        
        print(f"  距离：{order['logistics']['distance_km']}公里")
        print(f"  预计送达：{order['logistics']['estimated_date']}（约{order['logistics']['estimated_days']}天）")
        
        print("-" * 60)
    
    input("\n按回车键返回...")


def manage_shopping_cart(customer: Customer):
    """管理购物车"""
    cart = getattr(customer, 'cart', None)
    if not cart:
        cart = Cart()
        customer.cart = cart
    
    while True:
        print("\n" + "="*60)
        print("🛒 购物车管理")
        print("="*60)
        
        if not cart.items:
            print("购物车为空")
        else:
            print("\n购物车商品：")
            for i, item in enumerate(cart.items, 1):
                # 显示选中状态
                checkbox = "☑" if item.selected else "☐"
                print(f"{checkbox} {i}. 📦 {item.product_name}")
                print(f"   数量：{item.quantity} | 单价：{item.price}元 | 小计：{item.get_total()}元")
                print("-" * 40)
            
            selected_count = len(cart.get_selected_items())
            selected_total = cart.calculate_total(selected_only=True)
            print(f"\n已选中：{selected_count}件商品")
            print(f"💰 已选商品总金额：{selected_total}元")
            print(f"💰 购物车总金额：{cart.calculate_total()}元")
        
        print("\n操作选项：")
        print("1. ➕ 添加商品到购物车")
        print("2. ➖ 删除购物车商品")
        print("3. 🔄 修改商品数量")
        print("4. ☑️  选择/取消选择商品（必须先选择才能结算）")
        print("5. 🛒 结算选中商品（需要先执行选项4选择商品）")
        print("6. 🗑️  清空购物车")
        print("7. 📋 全选/全不选")
        print("8. 🔙 返回上一级")
        
        choice = input("\n请选择（1-8）：").strip()
        
        if choice == "1":
            # 添加商品
            keyword = input("\n🔍 请输入要添加的商品名称：").strip()
            if not keyword:
                print("❌ 商品名称不能为空！")
                continue
            
            products = Product.fuzzy_search(keyword)
            if not products:
                print("❌ 未找到匹配的商品！")
                continue
            
            print(f"\n找到 {len(products)} 个匹配商品：")
            for i, p in enumerate(products[:10], 1):
                print(f"{i}. {p.name} - {p.prize}元")
            
            try:
                idx = int(input(f"\n请选择商品（1-{min(len(products), 10)}）：").strip()) - 1
                if 0 <= idx < len(products):
                    product = products[idx]
                    quantity = int(input("请输入数量：").strip())
                    if quantity > 0:
                        cart.add_item(product.id, product.name, product.prize, quantity)
                        print(f"✅ 已添加 {product.name} x{quantity} 到购物车")
                        # 保存购物车数据
                        user_manager.save_users()
                    else:
                        print("❌ 数量必须大于0！")
                else:
                    print("❌ 选择无效！")
            except ValueError:
                print("❌ 输入无效！")
        
        elif choice == "2":
            # 删除商品
            if not cart.items:
                print("❌ 购物车为空！")
                continue
            
            try:
                idx = int(input(f"\n请选择要删除的商品（1-{len(cart.items)}）：").strip()) - 1
                if 0 <= idx < len(cart.items):
                    item = cart.items[idx]
                    cart.remove_item(item.product_id)
                    print(f"✅ 已删除 {item.product_name}")
                    # 保存购物车数据
                    user_manager.save_users()
                else:
                    print("❌ 选择无效！")
            except ValueError:
                print("❌ 输入无效！")
        
        elif choice == "3":
            # 修改数量
            if not cart.items:
                print("❌ 购物车为空！")
                continue
            
            try:
                idx = int(input(f"\n请选择要修改的商品（1-{len(cart.items)}）：").strip()) - 1
                if 0 <= idx < len(cart.items):
                    item = cart.items[idx]
                    new_quantity = int(input(f"请输入新数量（当前：{item.quantity}）：").strip())
                    if new_quantity > 0:
                        cart.update_quantity(item.product_id, new_quantity)
                        print(f"✅ 已更新 {item.product_name} 数量为 {new_quantity}")
                        # 保存购物车数据
                        user_manager.save_users()
                    else:
                        print("❌ 数量必须大于0！")
                else:
                    print("❌ 选择无效！")
            except ValueError:
                print("❌ 输入无效！")
        
        elif choice == "4":
            # 选择/取消选择商品
            if not cart.items:
                print("❌ 购物车为空！")
                continue
            
            # 显示购物车商品列表
            print("\n" + "="*60)
            print("📦 选择要结算的商品")
            print("="*60)
            print("\n购物车商品列表：")
            for i, item in enumerate(cart.items, 1):
                checkbox = "☑" if item.selected else "☐"
                status_text = "【已选中】" if item.selected else "【未选中】"
                print(f"{checkbox} {i}. {item.product_name} {status_text}")
                print(f"   └─ 数量：{item.quantity} | 单价：{item.price}元 | 小计：{item.get_total()}元")
            print("-" * 60)
            
            selected_count = len(cart.get_selected_items())
            print(f"\n当前已选中：{selected_count}件商品")
            print("💡 提示：商品状态 ☑ 已选中  |  ☐ 未选中")
            
            try:
                idx = int(input(f"\n请选择要切换状态的商品编号（1-{len(cart.items)}）：").strip()) - 1
                if 0 <= idx < len(cart.items):
                    item = cart.items[idx]
                    item.selected = not item.selected
                    status = "已选中" if item.selected else "已取消选中"
                    print(f"\n✅ {item.product_name} 状态已更新为：{status}")
                    
                    # 显示更新后的选中状态
                    selected_count = len(cart.get_selected_items())
                    print(f"\n📊 当前已选中：{selected_count}件商品")
                    if selected_count > 0:
                        selected_total = cart.calculate_total(selected_only=True)
                        print(f"💰 已选商品总金额：{selected_total}元")
                        print("💡 提示：可以执行选项5进行结算")
                    else:
                        print("💡 提示：请继续选择要购买的商品")
                else:
                    print("❌ 选择无效！")
            except ValueError:
                print("❌ 输入无效！")
        
        elif choice == "5":
            # 结算选中商品
            selected_items = cart.get_selected_items()
            if not selected_items:
                print("❌ 没有选中的商品，无法结算！")
                print("💡 提示：请先执行选项4选择要购买的商品，然后再执行结算操作")
                input("\n按回车键继续...")
                continue
            
            # 每个商品单独下单
            checkout_selected_items_separately(customer, selected_items, cart)
        
        elif choice == "6":
            # 清空购物车
            if cart.items:
                confirm = input("确认清空购物车？(y/n)：").strip().lower()
                if confirm == 'y':
                    cart.items.clear()
                    print("✅ 购物车已清空")
                    # 保存购物车数据
                    user_manager.save_users()
            else:
                print("购物车已经是空的")
        
        elif choice == "7":
            # 全选/全不选
            if not cart.items:
                print("❌ 购物车为空！")
                continue
            
            print("\n💡 提示：批量操作商品选择状态")
            print("\n1. 全选所有商品")
            print("2. 取消所有选择")
            sub_choice = input("\n请选择（1-2）：").strip()
            
            if sub_choice == "1":
                cart.select_all()
                selected_count = len(cart.get_selected_items())
                print(f"✅ 已全选所有商品（共 {selected_count} 件）")
                print("💡 提示：现在可以执行选项5进行结算")
            elif sub_choice == "2":
                cart.deselect_all()
                print("✅ 已取消全选")
                print("💡 提示：请通过选项4选择要购买的商品")
            else:
                print("❌ 输入无效！")
        
        elif choice == "8":
            break
        
        else:
            print("❌ 输入无效！")


def customer_menu(customer: Customer):
    """买家菜单"""
    while True:
        print("\n" + "="*50)
        print("🛒 买家功能菜单")
        print("="*50)
        print("1. 🔍 快速搜索商品")
        print("2. 🔎 高级搜索")
        print("3. 📋 查看搜索历史")
        print("4. 🎯 智能推荐")
        print("5. 🛒 购物车管理")
        print("6. 📦 我的订单")
        print("7. 🔙 返回主菜单")
        choice = input("\n请选择功能（1-7）：").strip()
        
        if choice == "1":
            keyword = input("\n🔍 请输入搜索关键词：").strip()
            if not keyword:
                print("❌ 搜索关键词不能为空！")
                continue
            
            products = Product.fuzzy_search(keyword)
            product = display_search_results(products, customer, keyword)
            if product:
                show_product_details(product, customer)
        
        elif choice == "2":
            advanced_search_menu(customer)
        
        elif choice == "3":
            show_search_history(customer)
        
        elif choice == "4":
            recommendation_menu(customer)
        
        elif choice == "5":
            manage_shopping_cart(customer)
        
        elif choice == "6":
            view_my_orders(customer)
        
        elif choice == "7":
            break
        
        else:
            print("❌ 输入无效，请重新选择！")


def advanced_search_menu(customer: Customer):
    """高级搜索菜单"""
    print("\n🔎 高级搜索")
    print("-" * 30)
    
    criteria = {}
    
    name = input("商品名称（可选，按回车跳过）：").strip()
    if name:
        criteria['name'] = name
    
    kind = input("商品类别（可选，按回车跳过）：").strip()
    if kind:
        criteria['kind'] = kind
    
    province = input("产地（可选，按回车跳过）：").strip()
    if province:
        criteria['province'] = province
    
    try:
        min_price = input("最低价格（可选，按回车跳过）：").strip()
        if min_price:
            criteria['min_price'] = float(min_price)
        
        max_price = input("最高价格（可选，按回车跳过）：").strip()
        if max_price:
            criteria['max_price'] = float(max_price)
    except ValueError:
        print("❌ 价格必须是数字！")
        return
    
    if not criteria:
        print("❌ 请至少输入一个搜索条件！")
        return
    
    products = Product.advanced_search(criteria)
    keyword = "高级搜索: " + ", ".join([f"{k}={v}" for k, v in criteria.items()])
    product = display_search_results(products, customer, keyword)
    if product:
        show_product_details(product, customer)


def show_search_history(customer: Customer):
    """显示搜索历史"""
    history = customer.get_search_history()
    if not history:
        print("\n📋 暂无搜索历史")
        return
    
    print("\n📋 搜索历史")
    print("=" * 50)
    for i, record in enumerate(reversed(history), 1):
        print(f"{i:2d}. 🔍 {record['keyword']}")
        print(f"     ⏰ {record['timestamp']}  📊 找到 {record['results_count']} 个结果")
        print("-" * 30)
    
    try:
        choice = input(f"\n选择要重新搜索的历史记录（1-{len(history)}，或按回车返回）：").strip()
        if choice:
            idx = int(choice) - 1
            if 0 <= idx < len(history):
                keyword = history[-(idx+1)]['keyword']
                if keyword.startswith("高级搜索: "):
                    print("❌ 高级搜索记录无法直接重新搜索")
                else:
                    products = Product.fuzzy_search(keyword)
                    product = display_search_results(products, customer, keyword)
                    if product:
                        show_product_details(product, customer)
    except (ValueError, IndexError):
        print("❌ 输入无效！")


def seller_menu(seller: Seller):
    """卖家菜单"""
    while True:
        print("\n" + "="*50)
        print("🏪 卖家功能菜单")
        print("="*50)
        print("1. 📦 查看我的商品")
        print("2. ➕ 添加新商品")
        print("3. 🔙 返回主菜单")
        choice = input("\n请选择功能（1-3）：").strip()
        
        if choice == "1":
            show_seller_products(seller)
        elif choice == "2":
            add_new_product(seller)
        elif choice == "3":
            break
        else:
            print("❌ 输入无效，请重新选择！")


def show_seller_products(seller: Seller):
    """显示卖家商品"""
    products = Product.get_merchant_products(seller.user_id)
    if not products:
        print("\n📦 您暂无商品！")
        return
    
    print("\n📦 我的商品：")
    print("="*50)
    for i, p in enumerate(products, 1):
        print(f"{i:2d}. 📦 {p.name}")
        print(f"     🆔 ID：{p.id}")
        print(f"     💰 价格：{p.prize}元  🏷️ 类别：{p.kind}")
        print("-" * 40)
    
    try:
        idx = int(input(f"\n选择要操作的商品（1-{len(products)}）：").strip()) - 1
        product = products[idx]
    except (ValueError, IndexError):
        print("❌ 输入无效！")
        return
    
    while True:
        print(f"\n📦 操作商品：{product.name}")
        print("-" * 40)
        print("1. 👀 查看评价")
        print("2. 💬 回复评价")
        print("3. ✏️  修改商品信息")
        print("4. 🔙 返回上一级")
        
        sub_choice = input("\n请选择（1-4）：").strip()
        
        if sub_choice == "1":
            show_merchant_product_comments(product)
        elif sub_choice == "2":
            reply_to_product_comment(product, seller)
        elif sub_choice == "3":
            update_product_info(product, seller)
        elif sub_choice == "4":
            break
        else:
            print("❌ 输入无效！")


def show_merchant_product_comments(product: Product):
    """商家查看商品评价"""
    if not product.comments:
        print("\n📝 暂无评价！")
        return
    
    print("\n📝 所有评价")
    print("="*50)
    for i, cmt in enumerate(product.comments, 1):
        print(f"{i:2d}. 👤 {cmt['nickname']}（{cmt['timestamp']}）")
        print(f"     ⭐ 评分：商品{cmt['product_rating']} 商家{cmt['merchant_rating']} 物流{cmt['logistics_rating']}")
        print(f"     💬 评价：{cmt['text']}")
        if cmt["merchant_reply"]:
            print(f"     🏪 已回复：{cmt['merchant_reply']['text']}")
        print(f"     👍 点赞：{cmt['likes']} | 💬 回复：{len(cmt['replies'])}")
        print("-" * 40)


def reply_to_product_comment(product: Product, seller: Seller):
    """商家回复评价"""
    if not product.comments:
        print("\n📝 暂无评价可回复！")
        return
    
    print("\n💬 回复评价")
    print("-" * 30)
    for i, cmt in enumerate(product.comments, 1):
        print(f"{i:2d}. 👤 {cmt['nickname']}：{cmt['text']}")
        if cmt["merchant_reply"]:
            print(f"     🏪 已回复：{cmt['merchant_reply']['text']}")
        print("-" * 30)
    
    try:
        cmt_idx = int(input(f"\n选择要回复的评价（1-{len(product.comments)}）：").strip()) - 1
        target_cmt = product.comments[cmt_idx]
        reply_text = input("请输入回复内容：").strip()
        product.merchant_reply(seller, target_cmt["comment_id"], reply_text)
    except (ValueError, IndexError):
        print("❌ 输入无效！")


def update_product_info(product: Product, seller: Seller):
    """修改商品信息"""
    print("\n✏️ 修改商品信息")
    print("-" * 30)
    print("可修改项：1.价格 2.产地")
    items = input("请选择要修改的项目（用逗号分隔，如1,2）：").strip().split(',')
    new_data = {}
    
    for item in items:
        if item == "1":
            try:
                new_prize = float(input("请输入新价格：").strip())
                new_data["prize"] = new_prize
            except ValueError:
                print("❌ 价格必须是数字！")
        elif item == "2":
            new_province = input("请输入新产地：").strip()
            new_data["province"] = new_province
        else:
            print(f"❌ 无效选项：{item}")
    
    if new_data:
        reason = input("请输入修改原因：").strip()
        if product.update_info(seller, new_data, reason):
            print("✅ 修改成功！")
            print(f"更新后信息：价格{product.prize}元，产地{product.province}")


def add_new_product(seller: Seller):
    """添加新商品"""
    print("\n➕ 添加新商品")
    print("-" * 30)
    
    try:
        name = input("商品名称：").strip()
        if not name:
            print("❌ 商品名称不能为空！")
            return
        
        province = input("产地：").strip()
        if not province:
            print("❌ 产地不能为空！")
            return
        
        prize = float(input("价格：").strip())
        if prize <= 0:
            print("❌ 价格必须大于0！")
            return
        
        province_id = input("产地ID（可选）：").strip() or "000"
        
        print("\n商品类别：")
        print("1. Food（食品）")
        print("2. Clothing（服装）")
        print("3. Book（图书）")
        print("4. Electronic Products（电子产品）")
        print("5. Daily product（日用品）")
        
        kind_choice = input("请选择类别（1-5）：").strip()
        kind_map = {
            "1": "Food",
            "2": "Clothing", 
            "3": "Book",
            "4": "Electronic Products",
            "5": "Daily product"
        }
        kind = kind_map.get(kind_choice, "Food")
        
        # 生成商品ID
        product_id = f"{kind[0].upper()}{len(Product._load_all_products()) + 1:03d}"
        
        # 创建商品
        product = Product(
            name=name,
            province=province,
            prize=prize,
            id_=product_id,
            province_id=province_id,
            merchant_id=seller.user_id,
            kind=kind
        )
        
        # 保存到文件
        product._save_to_file()
        print(f"✅ 商品添加成功！商品ID：{product_id}")
        
    except ValueError:
        print("❌ 输入格式错误！")
    except Exception as e:
        print(f"❌ 添加商品失败：{str(e)}")


def admin_menu(admin: Admin):
    """管理员菜单"""
    while True:
        print("\n" + "="*50)
        print("👑 管理员功能菜单")
        print("="*50)
        print("1. 👥 用户管理")
        print("2. 📦 商品管理")
        print("3. 📊 系统统计")
        print("4. 🔙 返回主菜单")
        choice = input("\n请选择功能（1-4）：").strip()
        
        if choice == "1":
            user_management_menu(admin)
        elif choice == "2":
            product_management_menu(admin)
        elif choice == "3":
            system_statistics_menu(admin)
        elif choice == "4":
            break
        else:
            print("❌ 输入无效，请重新选择！")


def user_management_menu(admin: Admin):
    """用户管理菜单"""
    while True:
        print("\n👥 用户管理")
        print("-" * 30)
        print("1. 查看所有用户")
        print("2. 查看买家列表")
        print("3. 查看卖家列表")
        print("4. 禁用/启用用户")
        print("5. 返回上一级")
        
        choice = input("\n请选择（1-5）：").strip()
        
        if choice == "1":
            show_all_users()
        elif choice == "2":
            show_users_by_type("Customer")
        elif choice == "3":
            show_users_by_type("Seller")
        elif choice == "4":
            toggle_user_status()
        elif choice == "5":
            break
        else:
            print("❌ 输入无效！")


def show_all_users():
    """显示所有用户"""
    users = user_manager.get_all_users()
    print(f"\n👥 所有用户（共{len(users)}个）")
    print("="*60)
    for i, user in enumerate(users, 1):
        status = "✅ 正常" if user.is_active else "❌ 禁用"
        print(f"{i:2d}. 👤 {user.username}（{user.user_type}）")
        print(f"     🆔 ID：{user.user_id}  📧 {user.email}")
        print(f"     📱 {user.phone}  📅 {user.created_at}")
        print(f"     {status}")
        print("-" * 40)


def show_users_by_type(user_type: str):
    """显示指定类型的用户"""
    users = user_manager.get_users_by_type(user_type)
    type_name = {"Customer": "买家", "Seller": "卖家", "Admin": "管理员"}.get(user_type, user_type)
    print(f"\n👥 {type_name}列表（共{len(users)}个）")
    print("="*60)
    for i, user in enumerate(users, 1):
        status = "✅ 正常" if user.is_active else "❌ 禁用"
        print(f"{i:2d}. 👤 {user.username}")
        print(f"     🆔 ID：{user.user_id}  📧 {user.email}")
        print(f"     📱 {user.phone}  📅 {user.created_at}")
        print(f"     {status}")
        if user_type == "Seller":
            print(f"     🏪 店铺：{user.shop_name}")
        print("-" * 40)


def toggle_user_status():
    """切换用户状态"""
    user_id = input("请输入要操作的用户ID：").strip()
    user = user_manager.get_user_by_id(user_id)
    
    if not user:
        print("❌ 用户不存在！")
        return
    
    if user.is_active:
        user.is_active = False
        print(f"✅ 已禁用用户：{user.username}")
    else:
        user.is_active = True
        print(f"✅ 已启用用户：{user.username}")
    
    user_manager.save_users()


def product_management_menu(admin: Admin):
    """商品管理菜单"""
    print("\n📦 商品管理")
    print("-" * 30)
    print("1. 查看所有商品")
    print("2. 按类别查看商品")
    print("3. 搜索商品")
    print("4. 返回上一级")
    
    choice = input("\n请选择（1-4）：").strip()
    
    if choice == "1":
        show_all_products()
    elif choice == "2":
        show_products_by_category()
    elif choice == "3":
        search_products_admin()
    elif choice == "4":
        return
    else:
        print("❌ 输入无效！")



def show_all_products():
    """显示所有商品"""
    products = Product._load_all_products()
    print(f"\n📦 所有商品（共{len(products)}个）")
    print("="*80)
    for i, product in enumerate(products, 1):
        print(f"{i:2d}. 📦 {product.name}")
        print(f"     🆔 ID：{product.id}  💰 价格：{product.prize}元")
        print(f"     🏷️ 类别：{product.kind}  📍 产地：{product.province}")
        print(f"     👤 商家：{product.merchant_id}")
        print("-" * 60)


def show_products_by_category():
    """按类别显示商品"""
    print("\n🏷️ 商品类别：")
    print("1. Food（食品）")
    print("2. Clothing（服装）")
    print("3. Book（图书）")
    print("4. Electronic Products（电子产品）")
    print("5. Daily product（日用品）")
    
    choice = input("请选择类别（1-5）：").strip()
    kind_map = {
        "1": "Food",
        "2": "Clothing",
        "3": "Book", 
        "4": "Electronic Products",
        "5": "Daily product"
    }
    kind = kind_map.get(choice)
    
    if not kind:
        print("❌ 无效选择！")
        return
    
    products = Product._load_all_products()
    filtered_products = [p for p in products if p.kind == kind]
    
    print(f"\n📦 {kind}类商品（共{len(filtered_products)}个）")
    print("="*80)
    for i, product in enumerate(filtered_products, 1):
        print(f"{i:2d}. 📦 {product.name}")
        print(f"     🆔 ID：{product.id}  💰 价格：{product.prize}元")
        print(f"     📍 产地：{product.province}  👤 商家：{product.merchant_id}")
        print("-" * 60)


def search_products_admin():
    """管理员搜索商品"""
    keyword = input("请输入搜索关键词：").strip()
    if not keyword:
        print("❌ 搜索关键词不能为空！")
        return
    
    products = Product.fuzzy_search(keyword)
    if not products:
        print("未找到匹配的商品！")
        return
    
    print(f"\n🔍 搜索结果：'{keyword}'（共{len(products)}个）")
    print("="*80)
    for i, product in enumerate(products, 1):
        print(f"{i:2d}. 📦 {product.name}")
        print(f"     🆔 ID：{product.id}  💰 价格：{product.prize}元")
        print(f"     🏷️ 类别：{product.kind}  📍 产地：{product.province}")
        print(f"     👤 商家：{product.merchant_id}")
        print("-" * 60)


def system_statistics_menu(admin: Admin):
    """系统统计菜单"""
    print("\n📊 系统统计")
    print("-" * 30)
    
    # 用户统计
    all_users = user_manager.get_all_users()
    customers = user_manager.get_users_by_type("Customer")
    sellers = user_manager.get_users_by_type("Seller")
    admins = user_manager.get_users_by_type("Admin")
    
    print(f"👥 用户统计：")
    print(f"   总用户数：{len(all_users)}")
    print(f"   买家：{len(customers)}")
    print(f"   卖家：{len(sellers)}")
    print(f"   管理员：{len(admins)}")
    
    # 商品统计
    products = Product._load_all_products()
    print(f"\n📦 商品统计：")
    print(f"   总商品数：{len(products)}")
    
    # 按类别统计
    kind_count = {}
    for product in products:
        kind_count[product.kind] = kind_count.get(product.kind, 0) + 1
    
    print(f"   类别分布：")
    for kind, count in kind_count.items():
        print(f"     {kind}：{count}个")
    
    # 评价统计
    total_comments = sum(len(p.comments) for p in products)
    print(f"\n📝 评价统计：")
    print(f"   总评价数：{total_comments}")
    
    input("\n按回车键返回...")


def register_menu():
    """注册菜单"""
    print("\n📝 用户注册")
    print("-" * 30)
    
    print("请选择用户类型：")
    print("1. 买家")
    print("2. 卖家")
    print("3. 返回主菜单")
    
    choice = input("请选择（1-3）：").strip()
    
    if choice == "3":
        return
    
    if choice not in ["1", "2"]:
        print("❌ 无效选择！")
        return
    
    user_type = "Customer" if choice == "1" else "Seller"
    
    username = input("用户名：").strip()
    if not username:
        print("❌ 用户名不能为空！")
        return
    
    password = input("密码：").strip()
    if not password:
        print("❌ 密码不能为空！")
        return
    
    email = input("邮箱：").strip()
    if not email:
        print("❌ 邮箱不能为空！")
        return
    
    phone = input("手机号：").strip()
    if not phone:
        print("❌ 手机号不能为空！")
        return
    
    kwargs = {}
    if choice == "2":  # 卖家
        shop_name = input("店铺名称：").strip()
        if not shop_name:
            print("❌ 店铺名称不能为空！")
            return
        kwargs["shop_name"] = shop_name
    
    user, message = user_manager.register_user(user_type, username, password, email, phone, **kwargs)
    
    if user:
        print(f"✅ {message}")
        print(f"用户ID：{user.user_id}")
    else:
        print(f"❌ {message}")


def login_menu():
    """登录菜单"""
    print("\n🔐 用户登录")
    print("-" * 30)
    
    username = input("用户名：").strip()
    if not username:
        print("❌ 用户名不能为空！")
        return
    
    password = input("密码：").strip()
    if not password:
        print("❌ 密码不能为空！")
        return
    
    user, message = user_manager.login_user(username, password)
    
    if user:
        print(f"✅ {message}")
        print(f"欢迎，{user.username}！")
        
        # 根据用户类型显示相应菜单
        if user.user_type == "Customer":
            customer_menu(user)
        elif user.user_type == "Seller":
            seller_menu(user)
        elif user.user_type == "Admin":
            admin_menu(user)
    else:
        print(f"❌ {message}")


def recommendation_menu(customer: Customer):
    """推荐菜单"""
    while True:
        print("\n🎯 智能推荐系统")
        print("="*50)
        print("1. 🧠 个性化推荐")
        print("2. 🔥 热门商品")
        print("3. 🏷️  分类推荐")
        print("4. 🔬 推荐算法对比")
        print("5. 📊 我的偏好分析")
        print("6. 🔙 返回上一级")
        
        choice = input("\n请选择功能（1-6）：").strip()
        
        if choice == "1":
            show_personalized_recommendations(customer)
        elif choice == "2":
            show_trending_products()
        elif choice == "3":
            show_category_recommendations(customer)
        elif choice == "4":
            show_algorithm_comparison(customer)
        elif choice == "5":
            show_user_preferences(customer)
        elif choice == "6":
            break
        else:
            print("❌ 输入无效，请重新选择！")


def show_personalized_recommendations(customer: Customer):
    """显示个性化推荐"""
    print("\n🧠 个性化推荐")
    print("-" * 40)
    
    try:
        recommendations = customer.get_personalized_recommendations(10)
        
        if not recommendations:
            print("📝 暂无推荐商品，请先浏览一些商品来建立您的偏好档案！")
            return
        
        print(f"🎯 为您推荐 {len(recommendations)} 个商品：")
        print("=" * 60)
        
        for i, product in enumerate(recommendations, 1):
            print(f"{i:2d}. 📦 {product.name}")
            print(f"     💰 价格：{product.prize}元")
            print(f"     🏷️  类别：{product.kind}  📍 产地：{product.province}")
            print(f"     🆔 ID：{product.id}")
            print("-" * 40)
        
        # 让用户选择查看详情
        try:
            choice = input(f"\n选择要查看的商品（1-{len(recommendations)}，0返回）：").strip()
            if choice == "0":
                return
            
            idx = int(choice) - 1
            if 0 <= idx < len(recommendations):
                product = recommendations[idx]
                customer.add_viewed_product(product.id)
                show_product_details(product, customer)
        except (ValueError, IndexError):
            print("❌ 输入无效！")
    
    except Exception as e:
        print(f"❌ 获取推荐失败：{str(e)}")


def show_trending_products():
    """显示热门商品"""
    print("\n🔥 热门商品")
    print("-" * 40)
    
    try:
        trending = recommendation_system.get_trending_products(days=7, num_recommendations=10)
        
        if not trending:
            print("📝 暂无热门商品数据！")
            return
        
        print(f"🔥 最近7天热门商品（共{len(trending)}个）：")
        print("=" * 60)
        
        for i, product in enumerate(trending, 1):
            print(f"{i:2d}. 📦 {product.name}")
            print(f"     💰 价格：{product.prize}元")
            print(f"     🏷️  类别：{product.kind}  📍 产地：{product.province}")
            print(f"     🆔 ID：{product.id}")
            print("-" * 40)
    
    except Exception as e:
        print(f"❌ 获取热门商品失败：{str(e)}")


def show_category_recommendations(customer: Customer):
    """显示分类推荐"""
    print("\n🏷️ 分类推荐")
    print("-" * 40)
    
    categories = ["Food", "Clothing", "Book", "Electronic Products", "Daily product"]
    category_names = {
        "Food": "食品",
        "Clothing": "服装", 
        "Book": "图书",
        "Electronic Products": "电子产品",
        "Daily product": "日用品"
    }
    
    print("请选择商品类别：")
    for i, category in enumerate(categories, 1):
        print(f"{i}. {category_names[category]}")
    
    try:
        choice = input("\n请选择类别（1-5）：").strip()
        idx = int(choice) - 1
        
        if 0 <= idx < len(categories):
            category = categories[idx]
            recommendations = customer.get_category_recommendations(category, 8)
            
            if not recommendations:
                print(f"📝 暂无{category_names[category]}类推荐商品！")
                return
            
            print(f"\n🏷️ {category_names[category]}类推荐商品：")
            print("=" * 60)
            
            for i, product in enumerate(recommendations, 1):
                print(f"{i:2d}. 📦 {product.name}")
                print(f"     💰 价格：{product.prize}元")
                print(f"     📍 产地：{product.province}")
                print(f"     🆔 ID：{product.id}")
                print("-" * 40)
        else:
            print("❌ 无效选择！")
    
    except (ValueError, IndexError):
        print("❌ 输入无效！")
    except Exception as e:
        print(f"❌ 获取分类推荐失败：{str(e)}")


def show_algorithm_comparison(customer: Customer):
    """显示推荐算法对比"""
    print("\n🔬 推荐算法对比")
    print("-" * 40)
    
    algorithms = {
        "collaborative": "协同过滤",
        "content": "内容推荐", 
        "popularity": "流行度推荐",
        "hybrid": "混合推荐"
    }
    
    print("不同算法的推荐结果对比：")
    print("=" * 60)
    
    for algo_key, algo_name in algorithms.items():
        try:
            recommendations = customer.get_recommendations(5, algo_key)
            print(f"\n🔬 {algo_name}：")
            
            if recommendations:
                for i, product in enumerate(recommendations, 1):
                    print(f"  {i}. {product.name} ({product.kind}) - {product.prize}元")
            else:
                print("  暂无推荐结果")
        
        except Exception as e:
            print(f"  ❌ {algo_name}算法出错：{str(e)}")
    
    print("\n" + "=" * 60)


def show_user_preferences(customer: Customer):
    """显示用户偏好分析"""
    print("\n📊 我的偏好分析")
    print("-" * 40)
    
    try:
        preferences = recommendation_system.behavior_tracker.get_user_preferences(customer.user_id)
        
        print("📈 您的购物偏好：")
        print("=" * 50)
        
        # 类别偏好
        if preferences["categories"]:
            print("🏷️ 最感兴趣的类别：")
            for category, count in preferences["categories"].most_common(3):
                print(f"   {category}: {count}次浏览")
        else:
            print("🏷️ 暂无类别偏好数据")
        
        # 价格偏好
        if preferences["price_range"]["min"] != float('inf'):
            print(f"\n💰 价格偏好范围：{preferences['price_range']['min']:.1f} - {preferences['price_range']['max']:.1f}元")
        else:
            print("\n💰 暂无价格偏好数据")
        
        # 产地偏好
        if preferences["provinces"]:
            print("\n📍 最感兴趣的产地：")
            for province, count in preferences["provinces"].most_common(3):
                print(f"   {province}: {count}次浏览")
        else:
            print("\n📍 暂无产地偏好数据")
        
        # 行为统计
        print(f"\n📊 行为统计：")
        print(f"   浏览商品：{len(preferences['viewed_products'])}个")
        print(f"   购买商品：{len(preferences['purchased_products'])}个")
        print(f"   评分商品：{len(preferences['rated_products'])}个")
        
        # 评分统计
        if preferences["rated_products"]:
            ratings = [data["rating"] for data in preferences["rated_products"].values()]
            avg_rating = sum(ratings) / len(ratings)
            print(f"   平均评分：{avg_rating:.1f}分")
    
    except Exception as e:
        print(f"❌ 获取偏好分析失败：{str(e)}")


def main():
    """主程序入口"""
    print("="*60)
    print("🛒 欢迎使用商品管理系统")
    print("="*60)
    
    while True:
        print("\n🏠 主菜单")
        print("-" * 30)
        print("1. 🔐 登录")
        print("2. 📝 注册")
        print("3. ❌ 退出系统")
        
        choice = input("\n请选择（1-3）：").strip()
        
        if choice == "1":
            login_menu()
        elif choice == "2":
            register_menu()
        elif choice == "3":
            print("\n👋 感谢使用，再见！")
            break
        else:
            print("❌ 请输入1-3之间的数字！")


if __name__ == "__main__":
    main()
